﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PickGold.Api
{
	public class FileEnumerator : IEnumerator<WIN32_FIND_DATA>, IEnumerable<WIN32_FIND_DATA>, IDisposable
	{
		private string _FindString;
		private IntPtr _FindHandle;
		private WIN32_FIND_DATA _FindResult;

		public FileEnumerator(string find)
		{
			if (string.IsNullOrEmpty(find))
				throw new ArgumentNullException();

			this._FindString = find;
		}

		public string FindString
		{
			get
			{
				return this._FindString;
			}
		}

		public IEnumerator<WIN32_FIND_DATA> GetEnumerator()
		{
			return this;
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return this.GetEnumerator();
		}

		public WIN32_FIND_DATA Current
		{
			get
			{
				if (this._FindHandle == IntPtr.Zero)
					throw new Exception();

				return this._FindResult;
			}
		}

		public void Dispose()
		{
			if (this._FindHandle != IntPtr.Zero)
				Kernel32.FindClose(this._FindHandle);
		}

		object IEnumerator.Current
		{
			get
			{
				return this.Current;
			}
		}

		public bool MoveNext()
		{
			if (this._FindHandle == IntPtr.Zero)
			{
				this._FindHandle = Kernel32.FindFirstFile(this._FindString, ref this._FindResult);
				if (this._FindHandle == IntPtr.Zero)
				{
					var i = Kernel32.GetLastError();
					if (i == 0)
						return false;

					throw i.GetException();
				}

				return true;
			}

			return Kernel32.FindNextFile(this._FindHandle, ref this._FindResult);
		}

		void IEnumerator.Reset()
		{
			this.Dispose();
		}
	}
}
